package com.yunkaweilai.android.activity.member;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.PreferencesUtils;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.CaptureActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.DialogPayInterface;
import com.yunkaweilai.android.interfaces.PopupEmployeeInterfaces;
import com.yunkaweilai.android.model.CheckMemberSendBean;
import com.yunkaweilai.android.model.CheckSendBean;
import com.yunkaweilai.android.model.CodeMsgBean;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.PayTypeModel;
import com.yunkaweilai.android.model.SendModel;
import com.yunkaweilai.android.model.integral.IntegralCreateOrderModel;
import com.yunkaweilai.android.model.member.IntegralPriceModel;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.PayErrorDialog;
import com.yunkaweilai.android.view.dialog.operation.DialogPayMoney;
import com.yunkaweilai.android.view.dialog.operation.OperationPayCashDialog;
import com.yunkaweilai.android.view.dialog.operation.OperationPayDialog;
import com.yunkaweilai.android.view.popup.ShopEmployeePopup2;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.picker.DatePicker;

/**
 * 会员充值
 */
public class MemberRechargeActivity extends BaseActivity implements DialogPayInterface, PopupEmployeeInterfaces {
    public static final String Recharge_MEMBER_MODEL = "Recharge_MEMBER_MODEL";
    public static final String Recharge_MEMBER_BUNDLE = "Recharge_MEMBER_BUNDLE";
    public static final String PERCENTAGES_STAFF_NAME = "PERCENTAGES_STAFF_NAME";
    public static final String PERCENTAGES_STAFF_ID = "PERCENTAGES_STAFF_ID";
    public static final int RECHARGE_TYPE = 131;//充值方式
    //选择充值方式
    public static final String PAY_TYPE_ID = "PAY_TYPE_ID";//活动id
    public static final String PAY_TYPE_MONEY = "PAY_TYPE_MONEY";//充值金额
    public static final String PAY_TYPE_GIVE_MONEY = "PAY_TYPE_GIVE_MONEY";//赠送金额
    public static final String PAY_TYPE_NAME = "PAY_TYPE_NAME";//充值方式名字
    public static final String PAY_TYPE_RULE = "PAY_TYPE_RULE";//充值规则
    public static final String PAY_TYPE_ALL_MONEY = "PAY_TYPE_ALL_MONEY";//充值总金额
    public static final String PAY_TYPE_IS_TRUE = "PAY_TYPE_IS_TRUE";//是否选择活动
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.id_tv_name)
    TextView idTvName;
    @BindView(R.id.id_tvcard_number)
    TextView idTvcardNumber;
    @BindView(R.id.id_tv_card_infor)
    TextView idTvCardInfor;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.id_tv_recharge_type)
    TextView idTvRechargeType;
    @BindView(R.id.id_rl_recharge_type)
    LinearLayout idRlRechargeType;
    @BindView(R.id.id_tv_recharge_money)
    TextView idTvRechargeMoney;
    @BindView(R.id.id_tv_give_money)
    TextView idTvGiveMoney;
    @BindView(R.id.id_tv_all_money)
    TextView idTvAllMoney;
    @BindView(R.id.id_tv_get_integral)
    TextView idTvGetIntegral;
    @BindView(R.id.id_rb_cash)
    RadioButton idRbCash;
    @BindView(R.id.id_rb_bank)
    RadioButton idRbBank;
    @BindView(R.id.id_rb_zfb)
    RadioButton idRbZfb;
    @BindView(R.id.id_rb_wx)
    RadioButton idRbWx;
    @BindView(R.id.id_rdg)
    RadioGroup idRdg;
    @BindView(R.id.id_tv_pey_type)
    TextView idTvPeyType;
    @BindView(R.id.id_edt_pey_money)
    TextView idEdtPeyMoney;
    @BindView(R.id.id_llayout_cash)
    LinearLayout idLlayoutCash;
    @BindView(R.id.id_tv_commission_name)
    TextView idTvCommissionName;
    @BindView(R.id.id_rl_commission_people)
    LinearLayout idRlCommissionPeople;
    @BindView(R.id.id_tv_remarks)
    EditText idTvRemarks;
    @BindView(R.id.content_view)
    ScrollView contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_tv_actual)
    TextView idTvActual;
    @BindView(R.id.id_tv_actual_money)
    TextView idTvActualMoney;
    @BindView(R.id.id_tv_confirm)
    TextView idTvConfirm;
    @BindView(R.id.id_tv_tuisong)
    TextView idTvTuisong;
    @BindView(R.id.id_check_sms)
    CheckBox idCheckSms;
    @BindView(R.id.id_check_vx)
    CheckBox idCheckVx;
    @BindView(R.id.id_check_print)
    CheckBox idCheckPrint;
    @BindView(R.id.id_check_next)
    CheckBox idCheckNext;
    @BindView(R.id.line_to_member)
    LinearLayout linearLayoutToMember;

    private Gson gson = new Gson();
    private MemberHeadModel model;
    private String payment_type = "cash";//支付方式
    //选择充值方式
    private String pay_type_id = "0";//充值方式id
    private String pay_type_rule = "";//充值规则
    private boolean isPayTrue = false;//是否选择充值方式
    private String allMoney = "0";
    private IntegralPriceModel integralPriceModel;
    private PayTypeModel payModel;
    private boolean sms = false;
    private boolean wechat = false;
    private boolean open_sms = false;
    private boolean print = false;

    public static void actionStart(Context context, MemberHeadModel model) {
        Intent intent = new Intent(context, MemberRechargeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(Recharge_MEMBER_MODEL, model);
        intent.putExtra(Recharge_MEMBER_BUNDLE, bundle);
        context.startActivity(intent);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_recharge);
        ButterKnife.bind(this);

        //让详情先显示出来
        linearLayoutToMember.setVisibility(View.VISIBLE);
        boolean aBoolean = PreferencesUtils.getBoolean(mAc, CommonConstants.RECHARGE_DAYING, false);
        idCheckPrint.setChecked(aBoolean);
        model = (MemberHeadModel) getIntent().getBundleExtra(Recharge_MEMBER_BUNDLE).getSerializable(Recharge_MEMBER_MODEL);
        initHeadView();
        initOtherView();
        initClick();
        initDate();
        initGetTuisong2();
    }

    private void initGetTuisong() {
        HttpRequest.postUrl(Api.GET_SEND_STATUS)
                .addParams("send_view", "Recharge")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            SendModel sendModel = gson.fromJson(json, SendModel.class);
                            if (sendModel != null) {
                                if ("1".equals(sendModel.getData().getInfo().getSend_sms_status()) && sms) {
                                    idCheckSms.setChecked(true);
                                }
                                if ("1".equals(sendModel.getData().getInfo().getSend_wechat_status()) && wechat) {
                                    idCheckVx.setChecked(true);
                                }
                            }
                        }

                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                    }
                });
    }

    private void initGetTuisong2() {
        clickable(false, "sms");
        clickable(false, "wechat");

        HttpRequest.postUrl(Api.CHECK_SEND)
                .addParams("view", "recharge")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        contentView.scrollTo(0, 0);
                        boolean checkcode = Utils.checkCode(mAc,json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            CheckSendBean checkSendBean = gson.fromJson(json, CheckSendBean.class);
                            if (checkSendBean.getData().getIs_check_print().equals("1")) {
                                print = true;
                                idCheckPrint.setClickable(true);
                                idCheckPrint.setAlpha((float) 1);
                            } else {
                                idCheckPrint.setClickable(false);
                                idCheckPrint.setAlpha((float) 0.3);
                                idCheckPrint.setChecked(false);//避免切换账号以后打钩残留的问题
                                print = false;
                            }
                            if (checkSendBean.getData().getIs_send_sms().equals("1")) {
                                open_sms = true;
                            } else {
                                open_sms = false;
                            }
                            selectMember(model.getCard_no());
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    //获取会员是否有手机或者微信
    private void selectMember(String card_no) {
        HttpRequest.postUrl(Api.CONSUME_MEMBER)
                .addParams("keyword", card_no)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(mAc,json);
                        if (checkcode) {

                            Gson gson = new Gson();
                            CheckMemberSendBean checkMemberSendBean = gson.fromJson(json, CheckMemberSendBean.class);
                            if (!StringUtils.isEmpty(checkMemberSendBean.getData().getMemberInfo().getMember_tel()) && open_sms) {
                                clickable(true, "sms");
                                sms = true;
                            } else {
                                clickable(false, "sms");
                                sms = false;
                            }
                            if (checkMemberSendBean.getData().getMemberInfo().getIs_push_wechat() == 1) {
                                clickable(true, "wechat");
                                wechat = true;
                            } else {
                                clickable(false, "wechat");
                                wechat = false;
                            }
                            initGetTuisong();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    private void clickable(boolean able, String type) {
        if (able) {
            if (type.equals("sms")) {
                idCheckSms.setClickable(true);
                idCheckSms.setAlpha((float) 1);
            }
            if (type.equals("wechat")) {
                idCheckVx.setClickable(true);
                idCheckVx.setAlpha((float) 1);
            }
            if (type.equals("next")) {
                idCheckNext.setClickable(true);
                idCheckNext.setAlpha((float) 1);
            }
        } else {
            if (type.equals("sms")) {
                idCheckSms.setClickable(false);
                idCheckSms.setAlpha((float) 0.3);
            }
            if (type.equals("wechat")) {
                idCheckVx.setClickable(false);
                idCheckVx.setAlpha((float) 0.3);
            }
            if (type.equals("next")) {
                idCheckNext.setClickable(false);
                idCheckNext.setAlpha((float) 0.3);
            }
        }
    }


    private int mYear, mMonth, mDay;

    private void initDate() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mYear = c.get(Calendar.YEAR);// 获取当前年份
        mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
    }


    private void initClick() {
        idRdg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.id_rb_bank:
                        payment_type = "bank";
                        idLlayoutCash.setVisibility(View.GONE);
                        break;
                    case R.id.id_rb_cash:
                        payment_type = "cash";
                        idLlayoutCash.setVisibility(View.VISIBLE);
                        idEdtPeyMoney.setText(idTvRechargeMoney.getText().toString() + "");
                        break;
                    case R.id.id_rb_wx:
                        payment_type = "wechat";
                        idLlayoutCash.setVisibility(View.GONE);
                        break;
                    case R.id.id_rb_zfb:
                        payment_type = "alipay";
                        idLlayoutCash.setVisibility(View.GONE);
                        break;
                    case R.id.id_rb_yue:
                        payment_type = "balance";
                        idLlayoutCash.setVisibility(View.GONE);
                        break;
                }
            }
        });

        idCheckPrint.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                PreferencesUtils.putBoolean(mAc, CommonConstants.RECHARGE_DAYING, isChecked);
            }
        });
        idCheckSms.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                saveSendStatus("send_sms", isChecked, idCheckSms);
            }
        });
        idCheckVx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                saveSendStatus("send_wechat", isChecked, idCheckVx);
            }
        });
        idCheckNext.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if ("再次消费提醒".equals(idCheckNext.getText().toString())) {
                        idCheckNext.setChecked(false);
                        initPickerData(idCheckNext);
                    }
                } else {
                    idCheckNext.setText("再次消费提醒");
                }
            }
        });
    }

    //时间选择
    private void initPickerData(final CheckBox tvView) {
        final DatePicker picker = new DatePicker(this);
        picker.setCanLoop(false);
        picker.setWheelModeEnable(true);
        picker.setTopPadding(15);
        picker.setRangeStart(2018, 1, 01);
        picker.setRangeEnd(2108, 11, 11);
        picker.setSelectedItem(mYear, mMonth, mDay);
        picker.setWeightEnable(true);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                tvView.setText(year + "-" + month + "-" + day);
                tvView.setChecked(true);
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    private void saveSendStatus(String sendType, boolean status, final CheckBox checkBox) {
        HttpRequest.postUrl(Api.SAVE_SEND_STATUS)
                .addParams("send_status", status ? "1" : "0")
                .addParams("send_type", sendType)
                .addParams("send_view", "Recharge")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc,json);
                        if (!checkCode) {
                            checkBox.setChecked(false);
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }


    private void initOtherView() {
        payModel = BaseApplication.getPayModel();
        if (payModel != null) {
            if ("1".equals(payModel.getData().getInfo().getIs_bank_pay())) {
                idRbBank.setVisibility(View.VISIBLE);
            } else {
                idRbBank.setVisibility(View.GONE);
            }
            if ("1".equals(payModel.getData().getInfo().getIs_wechat_pay())) {
                idRbWx.setVisibility(View.VISIBLE);
            } else {
                idRbWx.setVisibility(View.GONE);
            }
            if ("1".equals(payModel.getData().getInfo().getIs_alipay())) {
                idRbZfb.setVisibility(View.VISIBLE);
            } else {
                idRbZfb.setVisibility(View.GONE);
            }
        }
    }

    //头部信息
    private void initHeadView() {
        new TitleBuilder(mAc).setTitleText("会员充值").setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        Utils.MemberHeadImg(mAc, model.getMember_avatar(), model.getMember_sex(), idImgHead);
        idTvName.setText(model.getMember_name() + " (" + model.getLevel_name() + ": " + model.getCard_no() + ")");
        idTvCardInfor.setText("折扣：" + model.getDiscount() / 10 + "折   积分：" + model.getMember_points() + "   余额：" + model.getMember_price());


        Drawable drawable = getResources().getDrawable(R.drawable.selector_checkbox_style);
        //设置drawable对象的大小
        drawable.setBounds(0, 0, 40, 40);
        Drawable drawable2 = getResources().getDrawable(R.drawable.selector_checkbox_style);
        //设置drawable对象的大小
        drawable2.setBounds(0, 0, 40, 40);
        Drawable drawable3 = getResources().getDrawable(R.drawable.selector_checkbox_style);
        //设置drawable对象的大小
        drawable3.setBounds(0, 0, 40, 40);
        Drawable drawable4 = getResources().getDrawable(R.drawable.selector_checkbox_style);
        //设置drawable对象的大小
        drawable4.setBounds(0, 0, 40, 40);
        idCheckSms.setCompoundDrawables(drawable, null, null, null);
        idCheckVx.setCompoundDrawables(drawable2, null, null, null);
        idCheckPrint.setCompoundDrawables(drawable3, null, null, null);
        idCheckNext.setCompoundDrawables(drawable4, null, null, null);

    }

    @OnClick({R.id.line_to_member, R.id.id_img_head, R.id.id_rl_recharge_type, R.id.id_rl_commission_people, R.id.id_tv_confirm, R.id.id_edt_pey_money})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.line_to_member:
                MemberInfoListActivity.actionStart(mAc, model,"2");
                break;
            case R.id.id_edt_pey_money:
                if ("输入金额".equals(idEdtPeyMoney.getText().toString())) {
                    showToast("还未选择充值方式");
                } else {
                    new DialogPayMoney(mAc, R.style.dialog, new DialogPayMoney.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm, String content) {
                            if (confirm) {
                                idEdtPeyMoney.setText(Utils.ManageMoney(content));
                                if (!StringUtils.isEmpty(content) && !StringUtils.isEmpty(idTvRechargeMoney.getText().toString())) {
                                    idEdtPeyMoney.setText(Utils.ManageMoney(content));
                                }
                                dialog.dismiss();
                            }
                        }
                    }, idEdtPeyMoney.getText().toString(), "收款金额").show();
                }

                break;
            case R.id.id_rl_recharge_type://选择充值方式
                Intent intent = new Intent(mAc, RechargeModeActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(RechargeModeActivity.Recharge_Mode_MEMBER_MODEL, model);
                intent.putExtra(RechargeModeActivity.Recharge_Mode_MEMBER_BUNDLE, bundle);
                startActivityForResult(intent, RECHARGE_TYPE);
                break;
            case R.id.id_rl_commission_people://提成员工
                ShopEmployeePopup2 shopPopup = new ShopEmployeePopup2(mAc, employeeStr, Api.PERCENTAGES_RECHARGE);
                shopPopup.setInterface(MemberRechargeActivity.this);
                shopPopup.showPopupWindow();
                break;
            case R.id.id_tv_confirm://确认付款
                isRight();
                break;
            case R.id.id_img_head:
                Utils.ImageEnlage(mAc, "1", model.getMember_avatar(), model.getMember_sex());
                break;
        }
    }

    private String employeeStr = "";

    private void isRight() {
        if (model == null) {
            showToast("系统错误");
            return;
        }
        if (!isPayTrue) {
            showToast("未获取充值方式");
            return;
        }


        if (payment_type.equals("cash")) {
            if ("输入金额".equals(idEdtPeyMoney.getText().toString())) {
                showToast("未填写收款金额");
                return;
            }
            OperationPayCashDialog dialog = new OperationPayCashDialog(mAc, idTvRechargeMoney.getText().toString(), idEdtPeyMoney.getText().toString(), this);
            dialog.show();
        } else {
            PayTypeModel.DataBean.InfoBean info = payModel.getData().getInfo();
            if (payment_type.equals("wechat")) {
                if ("MtoS".equals(info.getWechat_scan_pay_type())) {
                    OperationPayDialog dialog = new OperationPayDialog(mAc, "￥ " + idTvRechargeMoney.getText().toString(), this, payment_type);
                    dialog.show();
                } else {
                    //调用扫码
                    getCameraManifest();
                }
            } else if (payment_type.equals("alipay")) {
                if ("MtoS".equals(info.getAlipay_scan_pay_type())) {
                    OperationPayDialog dialog = new OperationPayDialog(mAc, "￥ " + idTvRechargeMoney.getText().toString(), this, payment_type);
                    dialog.show();
                } else {
                    //调用扫码
                    getCameraManifest();
                }
            } else {
                OperationPayDialog dialog = new OperationPayDialog(mAc, "￥ " + idTvRechargeMoney.getText().toString(), this, payment_type);
                dialog.show();
            }
        }

    }

    //创建随意充值订单
    private void createOrder() {
        PostProcess postProcess = HttpRequest.postUrl(Api.CREATE_ORDER)
                .addParams("member_id", model.getId())
                .addParams("orderInfo[OrderInfo][recharge_price]", idTvRechargeMoney.getText().toString())
                .addParams("orderInfo[OrderInfo][recharge_free_price]", idTvGiveMoney.getText().toString())
                .addParams("payInfo[payment_type]", payment_type)
                .addParams("payment", idTvRechargeMoney.getText().toString())
                .addParams("remark", idTvRemarks.getText().toString())
                .addParams("SelectedEmployeeStr", employeeStr)
                .addParams("payInfo[cash_price]", idTvRechargeMoney.getText().toString())
                .addParams("payInfo[bank_price]", idTvRechargeMoney.getText().toString())
                .addParams("payInfo[wechat_price]", idTvRechargeMoney.getText().toString())
                .addParams("payInfo[alipay_price]", idTvRechargeMoney.getText().toString());
        if (idCheckNext.isChecked()) {
            postProcess.addParams("sendConsumeInfo[ConsumeAgain]", "ConsumeAgain");
            postProcess.addParams("sendConsumeInfo[consume_again_time]", idCheckNext.getText().toString());
        }
        postProcess
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            showToast("充值成功");
                            String member_points = model.getMember_points();
                            float points = Float.parseFloat(member_points);
                            if (integralPriceModel != null) {
                                model.setMember_points(points + integralPriceModel.getData().getSpecial_points() + integralPriceModel.getData().getPrice_points() + "");
                            }
                            String member_price = model.getMember_price();
                            float price = Float.parseFloat(member_price);
                            float money_all = Float.parseFloat(allMoney);
                            model.setMember_price(price + money_all + "");
                            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.MEMBER_LIST, true));
                            EventBus.getDefault().post(new Event.OtherTypeEvent(CommonConstants.MEMBER_INFO_LIST, true, model));
                            IntegralCreateOrderModel integralCreateOrderModel = gson.fromJson(json, IntegralCreateOrderModel.class);
                            RechargeSuccessActivity.actionStart(mAc, integralCreateOrderModel.getData().getTid(), sms, wechat, print);
                            finish();
                        } else {
                            CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
                            if (codeMsgBean.getMessage().contains("支付异常")) {
                                PayErrorDialog dialog = new PayErrorDialog(mAc, codeMsgBean.getMessage() + "");
                                dialog.setCanceledOnTouchOutside(false);
                                dialog.show();
                            } else {
                                showToast(codeMsgBean.getMessage() + "");
                            }
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();

//                        showToast("支付超时，请与对方联系。");
                    }
                });

    }

    //创建活动优惠充值订单
    private void createOrder1() {
        PostProcess postProcess = HttpRequest.postUrl(Api.CREATE_ORDER)
                .addParams("member_id", model.getId())
                .addParams("payInfo[get_price]", idEdtPeyMoney.getText().toString())
                .addParams("payInfo[payment_type]", payment_type)
                .addParams("orderInfo[PointsInfo][recharge_id]", pay_type_id)
                .addParams("orderInfo[PointsInfo][recharge_type]", pay_type_rule)
                .addParams("payment", idTvRechargeMoney.getText().toString())
                .addParams("remark", idTvRemarks.getText().toString())
                .addParams("SelectedEmployeeStr", employeeStr)
                .addParams("payInfo[cash_price]", idTvRechargeMoney.getText().toString())
                .addParams("payInfo[bank_price]", idTvRechargeMoney.getText().toString())
                .addParams("payInfo[wechat_price]", idTvRechargeMoney.getText().toString())
                .addParams("payInfo[alipay_price]", idTvRechargeMoney.getText().toString());
        if (idCheckNext.isChecked()) {
            postProcess.addParams("sendConsumeInfo[ConsumeAgain]", "ConsumeAgain");
            postProcess.addParams("sendConsumeInfo[consume_again_time]", idCheckNext.getText().toString());
        }
        postProcess
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            showToast("充值成功");
                            String member_points = model.getMember_points();
                            float points = Float.parseFloat(member_points);
                            if (integralPriceModel != null) {
                                model.setMember_points(points + integralPriceModel.getData().getSpecial_points() + integralPriceModel.getData().getPrice_points() + "");
                            }
                            String member_price = model.getMember_price();
                            float price = Float.parseFloat(member_price);
                            float money_all = Float.parseFloat(allMoney);
                            model.setMember_price(price + money_all + "");
                            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.MEMBER_LIST, true));
                            EventBus.getDefault().post(new Event.OtherTypeEvent(CommonConstants.MEMBER_INFO_LIST, true, model));
                            IntegralCreateOrderModel integralCreateOrderModel = gson.fromJson(json, IntegralCreateOrderModel.class);
                            RechargeSuccessActivity.actionStart(mAc, integralCreateOrderModel.getData().getTid(), sms, wechat, print);
                            finish();
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Exception e) {

                        dismissProgressDialog();
                    }
                });

    }

    //创建活动优惠充值订单
    private void createOrder2(String code) {
        PostProcess postProcess = HttpRequest.postUrl(Api.CREATE_ORDER)
                .addParams("member_id", model.getId())
                .addParams("payInfo[get_price]", idEdtPeyMoney.getText().toString())
                .addParams("payInfo[payment_type]", payment_type)
                .addParams("orderInfo[PointsInfo][recharge_id]", pay_type_id)
                .addParams("orderInfo[PointsInfo][recharge_type]", pay_type_rule)
                .addParams("payment", idTvRechargeMoney.getText().toString())
                .addParams("remark", idTvRemarks.getText().toString())
                .addParams("SelectedEmployeeStr", employeeStr)
                .addParams("payInfo[cash_price]", idTvRechargeMoney.getText().toString())
                .addParams("payInfo[bank_price]", idTvRechargeMoney.getText().toString())
                .addParams("payInfo[wechat_price]", idTvRechargeMoney.getText().toString())
                .addParams("payInfo[alipay_price]", idTvRechargeMoney.getText().toString());
        if (idCheckNext.isChecked()) {
            postProcess.addParams("sendConsumeInfo['ConsumeAgain']", "ConsumeAgain");
            postProcess.addParams("sendConsumeInfo['consume_again_time']", idCheckNext.getText().toString());
        }
        if (payment_type.equals("wechat")) {
            postProcess.addParams("payInfo[is_wechat_auth_code]", "1");
            postProcess.addParams("payInfo[wechat_auth_code]", code);
        } else if (payment_type.equals("alipay")) {
            postProcess.addParams("payInfo[is_alipay_auth_code]", "1");
            postProcess.addParams("payInfo[alipay_auth_code]", code);
        }
        postProcess
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCodeNoToast(mAc, json);
                        if (checkCode) {
                            showToast("充值成功");
                            String member_points = model.getMember_points();
                            float points = Float.parseFloat(member_points);
                            if (integralPriceModel != null) {
                                model.setMember_points(points + integralPriceModel.getData().getSpecial_points() + integralPriceModel.getData().getPrice_points() + "");
                            }
                            String member_price = model.getMember_price();
                            float price = Float.parseFloat(member_price);
                            float money_all = Float.parseFloat(allMoney);
                            model.setMember_price(price + money_all + "");
                            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.MEMBER_LIST, true));
                            EventBus.getDefault().post(new Event.OtherTypeEvent(CommonConstants.MEMBER_INFO_LIST, true, model));
                            IntegralCreateOrderModel integralCreateOrderModel = gson.fromJson(json, IntegralCreateOrderModel.class);
                            RechargeSuccessActivity.actionStart(mAc, integralCreateOrderModel.getData().getTid(), sms, wechat, print);
                            finish();
                        } else {
                            if (json.equals("您使用的私钥格式错误，请检查RSA私钥配置")){
                                dismissProgressDialog();
                                return;
                            }
                            CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
                            if (codeMsgBean.getMessage().contains("支付异常")) {
                                PayErrorDialog dialog = new PayErrorDialog(mAc, codeMsgBean.getMessage() + "");
                                dialog.setCanceledOnTouchOutside(false);
                                dialog.show();
                            } else {
                                showToast(codeMsgBean.getMessage() + "");
                            }
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Exception e) {
                        PayErrorDialog dialog = new PayErrorDialog(mAc, "支付异常，请与对方确认。");
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.show();
                        dismissProgressDialog();
                    }
                });

    }

    //获取积分接口
    private void getIntegral() {
        HttpRequest.postUrl(Api.GET_BALANCE_POINT)
                .addParams("member_id", model.getId())
                .addParams("payment", idTvRechargeMoney.getText().toString())
                .addParams("recharge_id", pay_type_id)
                .addParams("recharge_type", pay_type_rule)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            integralPriceModel = gson.fromJson(json, IntegralPriceModel.class);
                            if (integralPriceModel.getData().getSpecial_points() > 0) {
                                idTvGetIntegral.setText("金额积分：" + integralPriceModel.getData().getPrice_points() +
                                        "，额外积分：" + integralPriceModel.getData().getSpecial_points());
                            } else {
                                idTvGetIntegral.setText("金额积分：" + integralPriceModel.getData().getPrice_points());
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RECHARGE_TYPE) {
                pay_type_id = data.getStringExtra(PAY_TYPE_ID);
                idTvRechargeType.setText(data.getStringExtra(PAY_TYPE_NAME) + "");
                idTvRechargeMoney.setText(Utils.ManageMoney(data.getStringExtra(PAY_TYPE_MONEY)) + "");
                idTvGiveMoney.setText(Utils.ManageMoney(data.getStringExtra(PAY_TYPE_GIVE_MONEY)) + "");
                idTvActualMoney.setText(Utils.ManageMoney(idTvRechargeMoney.getText().toString()) + "");
                allMoney = data.getStringExtra(PAY_TYPE_ALL_MONEY);
                idTvAllMoney.setText(Utils.ManageMoney(allMoney));
                pay_type_rule = data.getStringExtra(PAY_TYPE_RULE);
                idEdtPeyMoney.setText(Utils.ManageMoney(data.getStringExtra(PAY_TYPE_MONEY)));
                isPayTrue = data.getBooleanExtra(PAY_TYPE_IS_TRUE, false);

                getIntegral();
            }
            if (requestCode == 101) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                String result = bundle.getString(CaptureActivity.RESULT);
                showProgressDialog("请稍等，正在支付中！");
                createOrder2(result);
            }
        }
    }


    //现金确认付款
    @Override
    public void payMoney() {
        showProgressDialog("请稍等，正在充值中！");
        if ("0".equals(pay_type_id)) {
            createOrder();
        } else {
            createOrder1();
        }
    }

    //获取照相机权限
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1;

    private void getCameraManifest() {
        MPermissions.requestPermissions(this, MY_PERMISSIONS_REQUEST_CAMERA, Manifest.permission.CAMERA);
    }

    private void getCamera() {
        Intent intent = new Intent(mAc, CaptureActivity.class);
        startActivityForResult(intent, 101);
    }

    @PermissionGrant(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestSuccess() {
        getCamera();
    }

    @PermissionDenied(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestError() {
        showToast("授权失败！");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return false;
    }

    @Override
    public void refresh(String empName, String empStr) {
        idTvCommissionName.setText(empName + "");
        employeeStr = empStr;
    }
}
